import React, { useState, useEffect } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import { View, Text, Input, Form, Button } from "@tarojs/components";
import FooterBtn from "@/components/FooterBtn";
import { setToken } from "@/src/service";
import * as api from "./api";
import * as collectApi from "../collectList/api";
import "./index.scss";

let timmer: any = null;

const Index: React.FC<{}> = () => {
  const [phone, setPhone] = useState("");
  const [countdownTime, setCountdownTime] = useState(60);

  const router = useRouter();
  const onSubmit = (e) => {
    console.log("e----------->>>", e.detail.value);
    const values = e.detail.value;
    if (!values.phone) {
      Taro.showToast({
        title: "请输入手机号",
        icon: "none",
      });
      return;
    }

    if (!values.verify_code) {
      Taro.showToast({
        title: "请输入短信验证码！",
        icon: "none",
      });
      return;
    }

    onLogin(values);
  };

  const onLogin = async (values) => {
    const { code } = await Taro.login();

    try {
      Taro.showLoading();
      const { result, status } = await api.customer_account_phoneregister({
        phone: values.phone,
        verify_code: values.verify_code,
        code,
      });
      if (status === "ok") {
        setToken({
          access_token: result.access_token,
          expire_time: result.expire_time,
          renew_flag: result.renew_flag,
        });
        getCollectList()
        if (router.params.params) {
          const params = JSON.parse(router.params.params);
          console.log('url-->>',`/pages/${params.redirectUrl}/index?${params.params.key}=${params.params.value}`)
          Taro.redirectTo({
            url: `/pages/${params.redirectUrl}/index?${params.params.key}=${params.params.value}`,
          });
        } else {
          Taro.navigateBack({ delta: 2 });
        }
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideLoading();
    }
  };

  const getCollectList = async () => {
    const { result, status } = await collectApi.customer_collection_getallcollectionsids({});
    if (status === "ok") {
      console.log("result---->>", result);
      Taro.setStorageSync('collectIds',result.goods_ids)
    }
  };

  const getPhoneCode = async () => {
    const reg = /^1\d{10}$/;
    if (!phone) {
      Taro.showToast({
        title: "请输入手机号",
        icon: "none",
      });
      return;
    }

    if (!reg.test(phone)) {
      Taro.showToast({
        title: "手机号格式错误",
        icon: "none",
      });
      return;
    }

    try {
      Taro.showLoading();
      const { result, status } = await api.customer_account_vcode_phone({
        number: phone,
        sms_type: "wechat_register",
      });
      if (status === "ok") {
        timmer = setInterval(() => {
          console.log("countdownTime------>>", countdownTime);
          setCountdownTime((countdownTime) => countdownTime - 1);
        }, 1000);
      }
    } catch (err) {
      console.log("err--------->>>", err);
    } finally {
      Taro.hideLoading();
    }
  };

  useEffect(() => {
    if (countdownTime <= 1) {
      clearInterval(timmer);
      setCountdownTime(60);
    }
  }, [countdownTime]);

  return (
    <View className="singer-form-page">
      <Form onSubmit={onSubmit}>
        <View className="form-area">
          <View className="form-item">
            <Input
              placeholder="请输入手机号"
              className="value"
              name="phone"
              placeholderClass="placeholder"
              type="number"
              maxlength={11}
              onInput={(e) => {
                setPhone(e.detail.value);
              }}
            />
          </View>
          <View className="form-item">
            <Input
              placeholder="请输入验证码"
              className="value"
              name="verify_code"
              placeholderClass="placeholder"
              type="number"
              maxlength={6}
            />
            {phone && countdownTime === 60 ? (
              <View className="code-btn" onClick={getPhoneCode}>
                获取验证码
              </View>
            ) : (
              <View className="code-btn code-btn__disabled">
                {countdownTime < 60
                  ? `(${countdownTime}s)后重发`
                  : "获取验证码"}
              </View>
            )}
          </View>
        </View>
        <Button formType="submit" className="submit">
          <FooterBtn content={<Text>登录</Text>} />
        </Button>
      </Form>
    </View>
  );
};

export default Index;
